package csci4448.android.workouttracker;

import java.util.List;

import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class ViewTabActivity extends Activity {
	
	private ListView sessions;
	private SessionModel _model = new SessionModel(this);

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_tab);
        
        sessions = (ListView)findViewById(R.id.session_list);
        sessions.setAdapter(getPreviousSessions());
        sessions.setOnItemClickListener(new OnItemClickListener() {

            public void onItemClick(AdapterView<?> list, View list_item, int position, long id) {
            	switchToViewSessionsActivity(position);
		    }
		});
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_view_tab, menu);
        return true;
    }
    
    public void onResume() {
        super.onResume();
		sessions.setAdapter(getPreviousSessions());
    }
    
    
    public ViewTabAdapter getPreviousSessions() {
		ViewTabAdapter adapter = new ViewTabAdapter(this, android.R.layout.simple_list_item_1);

		List<Session> Sessions;
		try {
			Sessions = _model.getSessions();
			for (Session s: Sessions) {
				adapter.add(new ViewTabItem(s.getSessionName(), s.getId()));
			}
		} catch (Exception e) {}
		
		if (adapter.getCount() == 0) {
			adapter.add(new ViewTabItem("No Previous Sessions Recorded.", -1));
			sessions.setChoiceMode(ListView.CHOICE_MODE_NONE);
		} else {
			sessions.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		}

		return adapter;
	}
    
    private void switchToViewSessionsActivity(int position){
    	Intent intent = new Intent(this, ViewSession.class);
		intent.putExtra("id", ((ViewTabItem)sessions.getItemAtPosition(position)).getId());
    	startActivity(intent);
    }
}
